/*
 * Copyright (C) qq:1219331697
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 *     
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.lzz.demo.zookeeper.curator.lock;

import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 
 * 模拟的共享资源， 这个资源期望只能单线程的访问，否则会有并发问题。
 * 
 * @author q1219331697
 *
 */
public class FakeLimitedResource {

	private final AtomicBoolean inUse = new AtomicBoolean(false);

	public void use() throws InterruptedException {
		
		// 真实环境中我们会在这里访问/维护一个共享的资源
		// 这个例子在使用锁的情况下不会非法并发异常IllegalStateException
		// 但是在无锁的情况由于sleep了一段时间，很容易抛出异常
		if (!inUse.compareAndSet(false, true)) {
			throw new IllegalStateException("Needs to be used by one client at a time");
		}

		try {
			Thread.sleep((long) (3 * Math.random()));
		} finally {
			inUse.set(false);
		}

	}

}
